//
//  ListenView.m
//  TotalDemo
//
//  Created by gujian on 16/3/24.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "ListenView.h"

static const NSInteger kHeight = 45;

@interface ListenView()

@property (nonatomic, weak) UILabel *stateLabel;

@end

@implementation ListenView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self == [super initWithFrame:frame]) {
        [self initSubviews];
    }
    
    return self;
}

- (void)initSubviews
{
    self.backgroundColor = [UIColor clearColor];
    self.height = kHeight;
    self.width = SCREEN_WIDTH;
    self.top = - kHeight;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHeight)];
    label.text = @"";
    label.textAlignment = NSTextAlignmentCenter;
    [self addSubview:label];
    _stateLabel = label;
    self.backgroundColor = [UIColor randomColor];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) {
        return;
    }
    
    [self removeObsvers];
    
    if (newSuperview) {
        _scrollView = (UIScrollView *)newSuperview;
        [self addObservers];
    
    }
    [self layoutIfNeeded];
    
}

#pragma mark - KVO

- (void)addObservers
{
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    [self.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeObsvers
{
    [self.superview removeObserver:self forKeyPath:@"contentOffset"];
    [self.superview removeObserver:self forKeyPath:@"contentSize"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint pos = [[change objectForKey:NSKeyValueChangeNewKey] CGPointValue];
        _stateLabel.text = [NSString stringWithFormat:@"(%f,%f)",pos.x,pos.y];
//        LotLog(@"pos:%f",_scrollView.contentInset.top);
        [self scrollViewContentOffSetDidChange:change];
    }else if ([keyPath isEqualToString:@"contentSize"])
    {
        LotLog(@"");
    }
}


- (void)scrollViewContentOffSetDidChange:(NSDictionary *)change
{
    
}














@end
